//
//  MeViewController.m
//  B
//
//  Created by lanou on 16/5/6.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "MeViewController.h"
#import "UIImage+Extension.h"
#import "UIView+QHExtension.h"
#import "LoginViewController.h"
#import "BaseNavigationController.h"
#import "AirViewController.h"           // 空气质量
#import "SettingViewController.h"       // 设置
#import "HealthyViewController.h"       // 健康指数


#define kTableViewHeaderDefH    200
#define kTableViewHeaderMinH    64
#define kTableViewTabH          80 // 第二个View视图的高度
@interface MeViewController ()<UITableViewDataSource,UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UISwitch *changeSkinSwitch; // 日夜切换开关
@property (weak, nonatomic) IBOutlet UITableView *MainTableView;
@property (weak, nonatomic) IBOutlet UIView *tableViewHeader;
@property (weak, nonatomic) IBOutlet UIImageView *TBVHeaderBG;
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UIView *TableViewTab;
@property (weak, nonatomic) IBOutlet UIImageView *level;    // 等级图标
@property (weak, nonatomic) IBOutlet UILabel *introduce;  // 个人签名

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *TBVHeaderH; // 用户背景图片高度
@property (weak, nonatomic) IBOutlet UIImageView *userIcon; // 用户头像

@property (nonatomic, copy) NSString *currentSkinModel;


@end

@implementation MeViewController
{
    CGFloat _defaultOffsetY;
}
- (UIView *)tableViewTab {
    if (!_TableViewTab) {
        UIView *view = [[UIView alloc] init];
        self.TableViewTab = view;
    }
    return _TableViewTab;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
    if (imageData) {
        self.TBVHeaderBG.image = [NSKeyedUnarchiver unarchiveObjectWithData:imageData];
    } else {
        self.TBVHeaderBG.image = [UIImage imageNamed:@"Q"];
    }
    // 注册cell
    [self.MainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"meCell"];
    
    // tableView
    _defaultOffsetY = -(kTableViewHeaderDefH + kTableViewTabH);
    [self.MainTableView setContentInset:UIEdgeInsetsMake(-_defaultOffsetY, 0, 0, 0)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.MainTableView setTableFooterView:[[UIView alloc] init]];
    
    _userIcon.image = [UIImage imageNamed:@"Mao10"].circleImage;
    _userIcon.userInteractionEnabled = YES;
    
    _TBVHeaderBG.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImage:)];
    [self.TBVHeaderBG addGestureRecognizer:tap];
    
    UITapGestureRecognizer *userTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserImage:)];
    [self.userIcon addGestureRecognizer:userTap];
    
}
- (void)changeUserImage:(UITapGestureRecognizer *)sender {
    NSLog(@"233333");
}

#pragma mark - 从图片库挑选图片
- (void)changeImage:(UITapGestureRecognizer *)sender {
    NSLog(@"--- 从图片库挑选图片");
    // 创建UIImagePickerController对象
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    // 设置代理
    picker.delegate = self;
    // 设置挑选出的图片是否可编辑
    picker.allowsEditing = YES;
    // 点击图片调用系统相册或拍照
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 判断当前设备此种类型是否可用
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"--- 当前设备有相机");
            picker.sourceType = UIImagePickerControllerSourceTypeCamera; // 调用相机
            [self presentViewController:picker animated:YES completion:^{}];
        } else {
            NSLog(@"当前设备没有相机");
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 模态出图片库
        [self.navigationController presentViewController:picker animated:YES completion:^{
        }];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
        }];
    }]];
    [self presentViewController:alert animated:YES completion:nil];

}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"图片信息---- %@", info);
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        NSLog(@"照相完成");
    } else {
        NSLog(@"图片库");
    }
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    // 把选择的图片赋值给UIImageView
    self.TBVHeaderBG.image = image;
    NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:self.TBVHeaderBG.image]; // 将图片归档之后
    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"image"]; // 保存在磁盘中
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark - 视图即将可见时调用
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"result"];
    if ([login isEqualToString:@"登录"]) { // 如果Login大于0 则表示用户账号已经登录
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickName"];
        [_userName setTitle:name forState:UIControlStateNormal];
    } else {
        [_userName setTitle:@"登录/注册" forState:UIControlStateNormal];
    }
    // 导航title先隐藏
    self.navigationController.navigationBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    // 设置导航条的背景图片
//    UIImage *image = nil;
//    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
//        image = [UIImage imageWithColor:[UIColor colorWithRed:34/255.0 green:30/255.0 blue:33/255.0 alpha:1.0]];
//    } else {
//        image = [UIImage imageWithColor:[UIColor colorWithRed:243/255.0 green:75/255.0 blue:80/255.0 alpha:1.0]];
//    }
//    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark 更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.MainTableView.backgroundColor = [UIColor blackColor];
        self.MainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.TableViewTab.backgroundColor = QHColor(47, 43, 49);
        self.userName.tintColor = QHColor(111, 109, 112);
        self.introduce.textColor = QHColor(111, 109, 112);
    } else {//日间模式
        self.MainTableView.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
        self.MainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.TableViewTab.backgroundColor = [UIColor whiteColor];
        self.userName.tintColor = [UIColor blackColor];
        self.introduce.textColor = [UIColor lightGrayColor];
    }
    [self.MainTableView reloadData];
}
#pragma mark - 头部image 滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat delta = offsetY - _defaultOffsetY;
    // 往上拖动，高度减少。
    CGFloat height = kTableViewHeaderDefH - delta;

    if (height < kTableViewHeaderMinH) {
        height = kTableViewHeaderMinH;
    }
    _TBVHeaderH.constant = height;
    // 设置导航条的背景图片
    CGFloat alpha = delta / (kTableViewHeaderDefH - kTableViewHeaderMinH);
    if (alpha > 0.3) {
        self.navigationController.navigationBarHidden = NO;
        // 当alpha大于1，导航条半透明，因此做处理，大于1，就直接=0.99
        if (alpha >= 1) {
            alpha = 0.99;
        }
    } else {
        self.navigationController.navigationBarHidden = YES;
    }
    // 设置导航条的背景图片
    UIImage *image = nil;
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        image = [UIImage imageWithColor:[UIColor colorWithRed:34/255.0 green:30/255.0 blue:33/255.0 alpha:alpha]];
    } else {
        image = [UIImage imageWithColor:[UIColor colorWithRed:243/255.0 green:75/255.0 blue:80/255.0 alpha:alpha]];
    }
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}
#pragma mark - Table view data source

#pragma mark -UITableViewDataSource 返回tableView有多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
#pragma mark -UITableViewDataSource 返回tableView每一组有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"meCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.textLabel.text = @"我的收藏";
        cell.imageView.image = [UIImage imageNamed:@"default_collection"];
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"健康指数";
        cell.imageView.image = [UIImage imageNamed:@"default_new_fans"];
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"天气情况";
        cell.imageView.image = [UIImage imageNamed:@"default_reviews_comment"];
    } else if (indexPath.row == 3) {
        cell.textLabel.text = @"夜间模式";
        cell.imageView.image = [UIImage imageNamed:@"default_my_order"];
        _changeSkinSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(ScreenWidth - 90, 7, 0, 0)];
        _changeSkinSwitch.onTintColor = QHColor(111, 109, 112);
        [self.changeSkinSwitch addTarget:self action:@selector(switchDidChange:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = _changeSkinSwitch;
        [cell.contentView addSubview:_changeSkinSwitch];
    } else {
        cell.textLabel.text = @"设置";
        cell.imageView.image = [UIImage imageNamed:@"icon_mine_setting@2x"];
    }
    
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        cell.backgroundColor = QHColor(35, 32, 36);
        cell.textLabel.textColor = QHColor(111, 109, 112);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.changeSkinSwitch.on = YES;
    } else {//夜间模式
        cell.backgroundColor =[UIColor whiteColor];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        self.changeSkinSwitch.on = NO;
    }

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.MainTableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        
    } else if (indexPath.row == 1) {
        [self.navigationController pushViewController:[HealthyViewController new] animated:YES];
    } else if (indexPath.row == 2) {
        [self.navigationController pushViewController:[AirViewController new] animated:YES];
    } else if (indexPath.row == 4) {
        [self.navigationController pushViewController:[SettingViewController new] animated:YES];
    } else {
        
    }
}
#pragma mark - 切换皮肤
- (void)switchDidChange:(UISwitch *)theSwitch {
    if (theSwitch.on == YES) {//切换至夜间模式
        [[NSUserDefaults standardUserDefaults] setObject:NightSkinModelValue forKey:CurrentSkinModelKey];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:DaySkinModelValue forKey:CurrentSkinModelKey];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
    // 发送切换颜色通知
    [[NSNotificationCenter defaultCenter] postNotificationName:SkinModelDidChangedNotification object:self];
}
#pragma mark - 登录注册
- (IBAction)loginAndRegist:(id)sender {
    if ([self.userName.titleLabel.text isEqualToString:@"登录/注册"]) {
        LoginViewController *loginVc = [LoginViewController new];
        BaseNavigationController *navi = [[BaseNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:navi animated:YES completion:nil];
    } else {
        return;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
